package BlackJack.View
{
	import BlackJack.Model.Events.MessageEvent;
	import BlackJack.Model.Events.TableEvent;
	import org.robotlegs.mvcs.Mediator;

	public class TableMediator extends Mediator
	{
		[Inject]
		public var view:Table;

		public function TableMediator()
		{
			super();
		}

		override public function onRegister():void
		{
			var type:String;
			for each (type in TableEvent.Events)
			{
				eventMap.mapListener(view, type, tableHandler);
			}
			eventMap.mapListener(view, TableEvent.C2S_DealingOK, socketHandler);
			eventMap.mapListener(view, TableEvent.C2S_CalculationOK, socketHandler);
			eventMap.mapListener(view, MessageEvent.Image, messageHandler);
			eventMap.mapListener(view, MessageEvent.Sound, messageHandler);
			for each (type in TableEvent.btnEvents)
			{
				eventMap.mapListener(view, type, socketHandler);
			}
		}

		private function tableHandler(event:TableEvent):void
		{
			eventDispatcher.dispatchEvent(new TableEvent(event.type));
			view.tableHandler(event);
		}

		private function messageHandler(event:MessageEvent):void
		{
			var s:String = '';
			var no:int;
			switch (event.type)
			{
				case MessageEvent.Sound:
				{
					s = s + main.client.MODEL;
					s = s + event.serial;
					s = s + '0' + Math.round(Math.random() * 2);
					no = int(s);
					socket.C2S_SoundMessage(no);
					break;
				}
				case MessageEvent.Image:
				{
					s = event.serial;
					no = int(s);
					socket.C2S_ImageMessage(no);
					break;
				}
			}
		}

		private function socketHandler(event:TableEvent):void
		{
			switch (event.type)
			{
				case TableEvent.C2S_DealingOK:
				{
					socket.C2S_DealingOK();
					break;
				}
				case TableEvent.C2S_CalculationOK:
				{
					socket.C2S_CalculationOK(1);
					break;
				}
				case TableEvent.Deal:
				{
					socket.C2S_PlayerDeal();
					break;
				}
				case TableEvent.Insurance:
				{
					socket.C2S_PlayerInsurance();
					break;
				}
				case TableEvent.Surrender:
				{
					socket.C2S_PlayerSurrender();
					break;
				}
				case TableEvent.Cancel:
				{
					socket.C2S_PlayerCancel();
					break;
				}
				case TableEvent.Hit:
				{
					socket.C2S_PlayerHit();
					break;
				}
				case TableEvent.Stay:
				{
					socket.C2S_PlayerStay();
					break;
				}
				case TableEvent.Double:
				{
					socket.C2S_PlayerDouble();
					break;
				}
				case TableEvent.Split:
				{
					socket.C2S_PlayerSplit();
					//socket.C2S_SoundMessage(No:int)
					//socket.C2S_ImageMessage(No:int)
					break;
				}
			}
			view.tableHandler(event);
		}

		public function get main():BlackJackMain
		{
			return contextView as BlackJackMain;
		}

		public function get socket():FGS12Processer
		{
			return main.socket;
		}
	}
}
